var express = require('express');
var router = express.Router();

//引入封装好的Query方法
const Query = require('../utils/db.js')
const { API_URL, verifyToken } = require('../utils/config.js')

//文件上传---------------------------
const formidable = require('formidable');
const fs = require('fs')
const path = require('path')
let timeStamp = require('time-stamp')
//文件上传---------------------------

/* GET home page. */
router.get('/demo2', function (req, res, next) {
  res.send('这是我们的个人中心模块')
});

//这是我们的个人中心

// 统一验证 在中间件中
router.use((req, res, next) => {
  let data = {}
  // console.log(req.headers.authorization);
  // res.send(req.headers.authorization)
  //后端验证token是否有效，如果有效代表登录了，则可以往下执行代码，如果token无效要提示请求登录 
  //req.query.

  if (!verifyToken(req.headers.authorization)) {
    data = {
      msg: '请登录',
      status: 500
    }
    res.send(data)
    return
  }

  // res.send('登录了，可以向下执行')
  next()
})



//1. -- 根据用户唯一标识：mid 查询当前用户的信息
// SELECT * FROM e_member WHERE mid = '1070931b-2221-4cd4-9846-d8d873a963c7'
router.get('/user', async (req, res, next) => {
  let data = {}

  //et mid = '1070931b-2221-4cd4-9846-d8d873a963c7' //用户唯一标识：需要传递过来
  let { mid = '' } = req.query
  if (!mid) {
    data = {
      msg: '请传递必要参数',
      status: 500,
    }
    res.send(data)
    return
  }

  //1. 定义sql
  let sql = `SELECT *,CONCAT('${API_URL}/uploads/avatars/',head_photo_url) AS head_photo_url FROM e_member WHERE mid = '${mid}'`
  //2. 使用引入的Query执行sql
  let { err, result } = await Query(sql)
  // res.send( err )
  if (err) {
    data = {
      msg: '稍后再试',
      status: 500,
    }
    res.send(data)
    return
  }

  //使用js中的delete关键字
  delete result[0].password //密码没有必要返回给用户

  data = {
    msg: 'OK',
    status: 200,
    result: result[0]
  }
  res.send(data)
});


//2. 更新用户信息，注意：唯独不包含更新头像和密码
//更新哪个用户：更新成什么 。
router.put('/user', async (req, res, next) => {
  let data = {}
  //
  let { realname = '', sex = '', city = '', birthdate = '', mid = '' } = req.body //put delete 同 post

  if (realname == '' || sex == '' || city == '' || birthdate == '' || mid == '') {
    data = {
      "msg": "请传递必要参数",
      "status": 500
    }
    res.send(data)
    return
  }

  // res.send('可以更新')
  // return
  console.log(birthdate);
  //1. 定义sql   UPDATE e_member SET realname = '张三' , sex=3, city='北京',birthdate=883584000000 WHERE mid='1070931b-2221-4cd4-9846-d8d873a963c7'
  let sql = `UPDATE e_member SET realname = '${realname}' , sex=${sex}, city='${city}', birthdate = '${birthdate}' WHERE  mid='${mid}'`
  //2. 使用引入的Query执行sql
  let { err, result } = await Query(sql)
  console.log(result);
  if (err) {
    data = {
      msg: '稍后再试',
      status: 500,
    }
    res.send(data)
    return
  }

  data = {
    msg: 'OK',
    status: 200
  }
  res.send(data)
});


//更新密码sql语句 ： UPDATE e_member set `password` = '13456566' WHERE mid = '1070931b-2221-4cd4-9846-d8d873a963c7' AND `password` = '418abc503af93a4cc52c5c870f94fea6'


//3. 更新头像接口
//文件上传
router.post('/uploadhead', async (req, res, next) => {
  
  //实例化接收文件数据的表单实例
  const form = formidable({
    //你实在把握不准，请把此路径改成绝对地址 path.join()
    uploadDir: 'uploads/avatars',//上传的临时路径
  })

  let data = {}
  form.parse(req, async (err, fields, files) => {
   
    //form.parse才是真正接收数据的方法，它是回调函数风格，没有我们等号赋值的风格。
    //fields : 普通的表单数据 比如用户名、密码、性别... 除type="file"以外的数据
    console.log(fields, '普通数据')
    console.log(files, '文件数据')
    let { mid = '' } = fields

    if (mid == '') {
      data = {
        msg: '请传递用户的id',
        status: 500
      }
      res.send(data)
      return
    }

    let name = files.f1.name
    let suffixName = path.extname(name) //得到了后缀名 带点的。       
    let t = timeStamp('YYYYMMDDHHmmss')
    let ran = (Math.random() + '').substring(2, 8)
    let head_photo_url = t + ran + suffixName //头像的新名称

    let oldpath = files.f1.path
    //你实在把握不准，请把此路径改成绝对地址 path.join()
    let newpath = 'uploads/avatars/' + head_photo_url
    fs.renameSync(oldpath, newpath)

    ///////////////////以下是sql的
    //1. 定义sql
    let sql = ` UPDATE e_member set head_photo_url = '${head_photo_url}' WHERE mid='${mid}'`
    //2. 使用引入的Query执行sql
    let { err: err1, result } = await Query(sql)
    // res.send( err )
    if (err1) {
      data = {
        msg: '稍后再试',
        status: 500,
      }
      res.send(data)
      return
    }

    let avatarUrl = API_URL + '/uploads/avatars/' + head_photo_url //要把新的图片地址返回，因为前端要让用户立马看到
    data = {
      msg: 'OK',
      status: 200,
      result: avatarUrl
    }
    res.send(data)

  })


  return
});


//4. 获取订单接口 必须传mid 
//SELECT *,CONCAT('http://localhost:3000/uploads/courses/',image_src) AS image_src FROM e_order AS o JOIN e_course AS c ON c.cid = o.cid WHERE mid='92f9793a-7c42-45c3-895b-4f6f1845def4'

router.get('/orders', async (req, res, next) => {
  let data = {}
  console.log(req.query.mid);
  let mid = req.query.mid
  if (!req.query.mid) {
    data = {
      msg: '请传入参数mid',
      status: '500'
    }
    res.send(data)
    return
  }
  let sql = `SELECT *,CONCAT('http://localhost:3000/uploads/courses/',image_src) AS image_src FROM e_order AS o JOIN e_course AS c ON c.cid = o.cid WHERE mid='${mid}'`
  let result = await Query(sql)
  console.log(result.result);
  data = {
    "msg": "OK",
    "status": 200,
    "result": result.result
  }
  res.send(data)
})
module.exports = router;
